package com.mogician.rabbitmq_demo.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mogician.rabbitmq_demo.R;
import com.mogician.rabbitmq_demo.bean.MyMessage;

import java.util.List;

public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder>
{
    private List<MyMessage> list;
    static class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView nicknameText;
        TextView messageText;
        public ViewHolder(@NonNull View itemView)
        {
            super(itemView);
            nicknameText = itemView.findViewById(R.id.nickname);
            messageText = itemView.findViewById(R.id.message_text);
        }
    }

    public MsgAdapter(List<MyMessage> list)
    {
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType)
    {
        View view;
        if(viewType == 0)
        {
            view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.item_message, viewGroup, false);
        }
        else
        {
            view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.item_message_self, viewGroup, false);
        }
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int positon)
    {
        MyMessage msg = list.get(positon);
        viewHolder.nicknameText.setText(msg.getId());
        viewHolder.messageText.setText(msg.getContent());
    }

    @Override
    public int getItemCount()
    {
        return list.size();
    }

    @Override
    public int getItemViewType(int position)
    {
        return list.get(position).isSelf() ? 1 : 0;
    }

    public void addData(MyMessage msg)
    {
        list.add(msg);
        notifyItemInserted(list.size());
    }

    public void addData(MyMessage msg, int positon)
    {
        list.add(positon, msg);
        notifyItemInserted(positon);
        if(positon < getItemCount())
            notifyItemRangeChanged(positon, getItemCount());
    }

    public void deleteData(MyMessage msg, int position)
    {
        list.remove(position);
        notifyItemRemoved(position);
        if(position < getItemCount())
            notifyItemRangeChanged(position, getItemCount());
    }
}
